package com.daikin.ktmustwrite.viewmodel.request

import androidx.lifecycle.MutableLiveData
import com.daikin.ktmustwrite.app.network.apiService
import com.daikin.ktmustwrite.app.network.stateCallback.ListDataUIState
import com.daikin.ktmustwrite.data.model.bean.AriticleResponse
import com.daikin.ktmustwrite.data.model.bean.BannerResponse
import com.daikin.ktmustwrite.data.repository.request.HttpRequestCoroutine
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.state.ResultState

class RequestHomeViewModel : BaseViewModel() {

    //页码 首页数据页码从0开始
    var pageNo = 0

    //首页文章列表数据
    var homeDataState: MutableLiveData<ListDataUIState<AriticleResponse>> = MutableLiveData()

    var bannerData : MutableLiveData<ResultState<ArrayList<BannerResponse>>> =MutableLiveData()
    /**
     *@Description: 获取轮播图数据
     */
    fun getBannerData(){
        request({ apiService.getBanner()},bannerData)
    }

    /**
     *@Description: 获取首页文章列表数据
     * @param  : isRefresh 是否是刷新，即第一页
     */
    fun getHomeData(isRefresh: Boolean){
        if (isRefresh){
            pageNo=0
        }
        request({ HttpRequestCoroutine.getHomeData(pageNo) }, {
            //请求成功
            pageNo++
            val listDataUiState =
                ListDataUIState(
                    isSuccess = true,
                    isRefresh = isRefresh,
                    isEmpty = it.isEmpty(),
                    hasMore = it.hasMore(),
                    isFirstEmpty = isRefresh && it.isEmpty(),
                    listData = it.datas
                )
            homeDataState.value = listDataUiState
        }, {
            //请求失败
            val listDataUiState =
                ListDataUIState(
                    isSuccess = false,
                    errMessage = it.errorMsg,
                    isRefresh = isRefresh,
                    listData = arrayListOf<AriticleResponse>()
                )
            homeDataState.value = listDataUiState
        })

    }
}